<template>
  <el-dialog v-model="dialogInfo.visible" :title="dialogInfo.title" :width="dialogInfo.width" align-center>
    <el-form ref="formRef" label-position="left" :model="formModel" :rules="formRules" label-width="120px">
      <el-row>
        <el-col :sm="24">
          <el-form-item label="设置结束时间" prop="endTime">
            <el-time-picker
                popper-class="i-el-time-popper-picker"
                v-model="formModel.EndTime"
                placeholder="请设置时间"
                value-format="HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="添加课程" prop="degreeType">
            <el-col :span="8">
              <el-select clearable class="w100 pr-3" style="box-sizing: border-box;" v-model="formModel.AcademyId" placeholder="请选择学院" autocomplete="off" @change="getMajorList">
                <el-option v-for="item in academyOption" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select clearable :disabled="!formModel.AcademyId" class="w100 pr-3" style="box-sizing: border-box;" v-model="formModel.MajorId" placeholder="请选择专业" autocomplete="off" @change="getCourseList">
                <el-option v-for="item in majorOption" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select clearable class="w100" :disabled="!formModel.MajorId" v-model="formModel.CourseId" placeholder="请选择课程" autocomplete="off">
                <el-option v-for="item in courseOption" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="教师姓名" prop="TeacherId">
            <el-select
                v-model="formModel.TeacherId"
                style="width: 240px"
                filterable
                remote
                :remote-method="getTeacherList"
                clearable
                :options="teacherOption"
                :loading="teacherLoading"
                placeholder="请输入搜索教师"
            >
              <el-option v-for="item in teacherOption" :key="item.Id" :label="item.Academy.name+' - ' + item.name" :value="item.Id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="info" plain @click="onCancel()">取消</el-button>
        <el-button type="primary" @click="onSubmit()" :loading="submitLoading">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 */
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import { getNewObj } from '@/utils/EsCommon';
import {liveTaskParams, liveTaskTypeList, taskForm} from '@/apis/model/LiveTaskModel';
import moment from "moment";




// ======================================================
//                      变量声明
// ======================================================

// emit
const emit = defineEmits(['success']);
// 表单数据
const formAttrs = getNewObj({
  "RoomId":1,
  "RecordIp":"",
  'ClassDay':"",
  'AcademyId':null,
  'MajorId':null,
  "RecordIds":"0,1,2,3,4,100",//先写死
  "EndTime":"",
  "TeacherId":null,
  "CourseId":null,
  "enable":1,
  "TaskType":2,//TaskType字段1、按节次建立的排程，2、自定义的排程
});

const formModel = ref(Object.assign({}, formAttrs));
// 弹窗信息
const dialogInfo = ref({
  visible: false,
  title: '',
  width: '635px',
})
// 表单组件的引用实例
const formRef = ref(null);

// 选项数据
const submitLoading =  ref(false)
const liveTaskTypeOption = ref(liveTaskTypeList);
const academyOption = ref([]);
const majorOption = ref([]);
const courseOption = ref([]);
const teacherLoading = ref(false);
const teacherOption = ref([]);

const campusOption = ref([]);
const buildingOption = ref([]);
const roomOption = ref([]);
// 表单校验规则
const formRules = ref({
  name: [{ required: true, trigger: "blur", message: "请输入教室名称" }],
})

// ======================================================
//                      点击操作
// ======================================================

// 点击提交按钮
const onSubmit = () => {
  submitLoading.value = true
  formRef.value.validate((valid, fields) => {
    if (!valid) {
      console.log('表单校验失败：', fields);
      return;
    }
    const form = JSON.parse(JSON.stringify(formModel.value))
    form.ClassDay = moment().format('YYYY-MM-DD')
    EsAjax.post(ApiUrls.recordTaskTest, {
      "RoomId": form.RoomId,
      "ClassDay": form.ClassDay,
      // "StartTime": form.StartTime,
      "EndTime": form.EndTime,
    }).then((_res) => {
      if (_res.data.code !== 200) {
        ElMessage.warning(_res.data.msg);
        return;
      }
      let url = ApiUrls.recordTaskAdd;
      EsAjax.post(url, form).then(res => {
        if (res.data.code !== 200) {
          ElMessage.warning(res.data.msg);
          return;
        }
        dialogInfo.value.visible = false;
        ElMessage.success('提交成功');
        emit('success');
      }).catch(err => {
        ElMessage.error('网络错误：' + err.message);
      }).finally(()=>  submitLoading.value = false)
    }).catch(err => {
      ElMessage.error('网络错误：' + err.message);
      submitLoading.value = false
    })
  })
}

// 点击取消按钮
const onCancel = () => {
  formModel.value = Object.assign({}, formAttrs);
  formRef.value.resetFields();
  dialogInfo.value.visible = false;
}
// ======================================================
//                      处理事件
// ======================================================

// 加载数据
const show = async (id, title, item = null, width = '635px') => {
  dialogInfo.value.title = title;
  dialogInfo.value.width = width;
  dialogInfo.value.visible = true;
  formModel.value = Object.assign({}, formAttrs)
  // 加载详情数据
  formModel.value.RoomId = item.id
  formModel.value.RecordIp = item.recordingIp
  // if (id) {
  //   formModel.value = Object.assign({ ...formAttrs }, getNewObj(item));
  // }
  getAcademyList()
  // getCampusList();
  // getRoomList();
  // getTeacherList();
}

const getAcademyList = () => {
  EsAjax.post(ApiUrls.academyList, { params: {} }).then(res => {
    console.log(res)

    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    let { list } = res.data.data
    academyOption.value = list;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}

const getMajorList = () => {
  if(formModel.value.AcademyId) {
    EsAjax.post(ApiUrls.majorList, {AcademyId: formModel.value.AcademyId}).then(res => {
      if (res.data.code !== 200) {
        ElMessage.warning(res.data.msg);
        return;
      }
      let {list} = res.data.data
      majorOption.value = list;
    }).catch(err => {
      ElMessage.error(err.message);
    })
  }
  formModel.value.MajorId = null
  formModel.value.CourseId = null
  majorOption.value = [];
  courseOption.value = [];
}
const getCourseList = () => {
  if(formModel.value.MajorId && formModel.value.AcademyId){
    EsAjax.post(ApiUrls.courseList, { AcademyId:formModel.value.AcademyId,MajorId:formModel.value.MajorId}).then(res => {
      console.log(res)
      if (res.data.code !== 200) {
        ElMessage.warning(res.data.msg);
        return;
      }
      let { list } = res.data.data
      courseOption.value = list;
    }).catch(err => {
      ElMessage.error(err.message);
    })
  } else{
    formModel.value.CourseId = null
    courseOption.value = [];
  }

}

const getCampusList = () => {
  EsAjax.post(ApiUrls.campusList, { params: {} }).then(res => {
    console.log(res)
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    let { list } = res.data.data
    campusOption.value = list;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}
const getBuildingList = () => {
  EsAjax.post(ApiUrls.buildingList, { params: {} }).then(res => {
    console.log(res)

    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    let { list } = res.data.data
    buildingOption.value = list;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}
const getRoomList = () => {
  EsAjax.post(ApiUrls.roomList, { params: {} }).then(res => {
    console.log(res)

    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    let { list } = res.data.data
    roomOption.value = list;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}
const getTeacherList = (name) => {
  if(name){
    teacherLoading.value = true
    EsAjax.post(ApiUrls.teacherList, { role: 1,realName:name }).then(res => {
      if (res.data.code !== 200) {
        ElMessage.warning(res.data.msg);
        return;
      }
      let { list, count } = res.data.data
      teacherOption.value = list;
    }).catch(err => {
      ElMessage.error(err.message);
    }).finally(()=>{
      teacherLoading.value = false
    })
  }else{
    teacherOption.value = [];
  }
}

defineExpose({
  show
})
</script>

<style scoped>
</style>
